var jsonData;
var environmentBarChartImgData;
var environmentStackedColumnChartImgData;
/**
 * Global variable to hold overhead table data across different select options
 */
var displayChartOverHead;

google.load("visualization", "1", {packages : ["corechart" , "imagechart", "table"]});
google.setOnLoadCallback(init);

$(document).ready(function(){
	
	$("#btnExport").click(function() {
		exportChart();
	});
	
	$('#envReq').change(function(){
		var selectedText = $("#envReq option:selected").text();
		$(".title").empty().html(selectedText);
	});
	
	$('#range').change(function() {
		var selectedText = $("#range option:selected").text();
		$("#percentRange").empty().html(selectedText);
	});
	

	$('#incidenceOfOccurance').change(function() {
		                var selected = this.value;
						var selectedText = $("#incidenceOfOccurance option:selected").text();
						$("#change").empty().html(selectedText);
						loadData(selected);
					});
});

function init(){
	initCharts();
}

function initCharts(){
	initEnvbarChart();
	initStackedColumnChart();
}

function initEnvbarChart(){
	
	var data = google.visualization.arrayToDataTable([['occupationalGrp Element','occupational Group Percent'],[ '', 0]]);

	var options = {
		title : 'Incidence of requirements By Occupational Group',
		legend : {
			position : 'none'
		},
		chartArea : {
			width : "50%",
			height : "70%"
		},
		hAxis : {
			title : 'Percentage of Employees Required',
			minValue : 0,
			maxValue : 100,
			tooltip : {
				trigger : 'selection'
			}
		},
	};

	var ac = new google.visualization.BarChart(document.getElementById('env_BarChart_div'));
	ac.draw(data, options);
}

function initStackedColumnChart() {
	var data = new google.visualization.arrayToDataTable([['occupationalGrp Element','notPresent Percent','almostNever Percent','occasionally Percent','frequently Percent','constantly Percent'],['', 0, 0, 0, 0, 0 ]]);
	  var options = {
          legend: {position: 'none'},
	      chartArea: {width:'90%', height:'60%', left : 75},
	      isStacked: true,
	      vAxis: {title: 'Percentage of Employees Required', minValue: 0, maxValue:100}
	  };
	                                   	  
	  var ac = new google.visualization.ColumnChart(document.getElementById('env_table_div'));
	  ac.draw(data, options);
}

function exportChart(){
	
}

function drawCharts(chartData){
	drawEnvBarChart(chartData.envExposureByOccList);
	drawEnv_stacked(chartData.envIncidenceSummaryList);
	drawEnvironment_overhead_Table(chartData.envExposureByOccList,3);
	displayChartOverHead=chartData.envExposureByOccList;
	//drawEnvironmentOverheadPopUpChart(chartData.overheadTableDetailList);
}

function drawOverAllDataTable(chartData){
	drawEnvTable(chartData.envIncidenceSummaryList);
}

function drawEnvBarChart(chartData){
	var dataArray = [];
	var options = {
		legend : { position : 'none', color : 'black'},
		hAxis : { title : 'Percentage of Employees Required'},
		vAxis : { textStyle : {
				color : 'black',
				fontName : 'Chango',
				fontSize : 10.5
			},
			tooltip : {
				trigger : 'selection'
			},
			format : '#%'
		},
		 colors: ['#009933'],
		chartArea : {
			width : "58%",
			height : "75%",
			left : 245
			
		},
		};

	var gdata = new google.visualization.DataTable();
	gdata.addColumn("string", "occupationalGrp Element");
	gdata.addColumn("number", "occupational Group Percent");
	$.each(chartData,function(i, obj) {
				dataArray.push([obj.occupationalGroup,obj.percentage]);
			});

	gdata.addRows(dataArray);

	var chart = new google.visualization.BarChart(document.getElementById('env_BarChart_div'));
	var formatter = new google.visualization.NumberFormat({
		suffix : '%'
	});
	formatter.format(gdata, 1);
	google.visualization.events.addListener(chart, 'ready', function() {
		environmentBarChartImgData = chart.getImageURI();
	});

	chart.draw(gdata, options);
}

function drawEnvTable(chartData) {
	
	var dataArray = [];
	var options = {

		legend : {
			position : 'none'
		},
		chartArea : {
			width : '80%',
			height : '60%'
		},
		alternatingRowStyle  : true,
	};

	var gdata = new google.visualization.DataTable();
	gdata.addColumn('string', 'Occupational Group' );
	gdata.addColumn('number', 'Not Present');
	gdata.addColumn('number', 'Almost Never' );
	gdata.addColumn('number', 'Occasionally' );
	gdata.addColumn('number', 'Frequently');
	gdata.addColumn('number', 'Constantly');
	$.each(chartData, function(i, obj) {
	dataArray.push([obj.occupationalGroup,obj.notPresent,obj.almostnever,obj.occasionally,obj.frequently,obj.constantly]);
	});
	gdata.addRows(dataArray);

	var table = new google.visualization.Table(document.getElementById('env_table_div'));
	var formatter = new google.visualization.NumberFormat({
		suffix : '%'
	});
	formatter.format(gdata, 1);
	formatter.format(gdata, 2);
	formatter.format(gdata, 3);
	formatter.format(gdata, 4);
	formatter.format(gdata, 5);

	var colorFormatter = new google.visualization.ColorFormat();
	colorFormatter.addRange(0.00, 50.00, 'white', 'orange');
	colorFormatter.format(gdata, 1);
	table.draw(gdata, options);
}

function drawEnv_stacked(chartData) {
	var dataArray = [];
	
	var options = {
		legend : {
			position : 'top',
				top : 100
		},
		vAxis: {title: 'Percentage of Employees Required', minValue: 0, maxValue:100},
		chartArea : {
			width : '80%',
			height : '52%',
			left : 100,
			top : 75
		},
		hAxis : { textStyle : {
			color : 'black',
			fontName : 'Chango',
			fontSize : 10.5
		},
		tooltip : {trigger : 'selection'},
		format : '#%'
	},
		isStacked : true
		};

	var gdata = new google.visualization.DataTable();
	gdata.addColumn('string', 'Occupational Group');
	gdata.addColumn('number', 'Not Present');
	gdata.addColumn('number', 'Almost Never');
	gdata.addColumn('number', 'Occasionally');
	gdata.addColumn('number', 'Frequently');
	gdata.addColumn('number', 'Constantly');
	$.each(chartData, function(i, obj) {
	dataArray.push([obj.occupationalGroup, obj.notPresent,obj.almostnever, obj.occasionally,obj.frequently, obj.constantly]);
	});

	gdata.addRows(dataArray);

	var chart = new google.visualization.ColumnChart(document.getElementById('env_table_div'));
	
	google.visualization.events.addListener(chart, 'ready', function() {
		environmentStackedColumnChartImgData = chart.getImageURI();
	});
	
	var formatter = new google.visualization.NumberFormat({
		suffix : '%'
	});
	formatter.format(gdata, 1);
	formatter.format(gdata, 2);
	formatter.format(gdata, 3);
	formatter.format(gdata, 4);
	formatter.format(gdata, 5);
	chart.draw(gdata, options);
}

function displayDataOnChangeOfCondition(displayConditionValue){
	drawEnvironment_overhead_Table(displayChartOverHead, displayConditionValue);
}

function drawEnvironment_overhead_Table(chartData,displayCondition) {
    var dataArray = [];
    var options = {

        legend : {
            position : 'none'
        },
        chartArea : {
            width : '80%',
            height : '80%'
        },
       
        sort : [ 'enable' ],
        sortAscending : [ true ],
    };
    
    var gdata = new google.visualization.DataTable();
    gdata.addColumn("string", "Occupational Group");
    gdata.addColumn("number", "Occupational Group Percent");
    
    $.each(chartData, function(i, obj) {
    	if(displayCondition==3) { 
            if(obj.percentage >= 50 && obj.percentage <75)
				dataArray.push([obj.occupationalGroup,obj.percentage]);
             }
    else if(displayCondition == 1){
    		if(obj.percentage >= 0 && obj.percentage <25)
				dataArray.push([obj.occupationalGroup,obj.percentage]);
    	}else if(displayCondition==2){
            if(obj.percentage >= 25 && obj.percentage <50)
				dataArray.push([obj.occupationalGroup,obj.percentage]);
     } else if(displayCondition==4){
            if(obj.percentage >= 75 && obj.percentage <100)
				dataArray.push([obj.occupationalGroup,obj.percentage]);
        } 
    });

    newDataArray = dataArray.sort();
    gdata.addRows(newDataArray);
    var table = new google.visualization.Table(document.getElementById('env_overHead'));
    var formatter = new google.visualization.NumberFormat({
        suffix : '%'
    });
    formatter.format(gdata, 1);
    table.draw(gdata, options);

    google.visualization.events.addListener(table, 'select', selectHandler);

function selectHandler(){
	var selection = table.getSelection();
	for(var i = 0 ; i< selection.length; i++){
		var item = selection[i];
		if(item.row==9){
			$("#modal").modal('show');
		}
	}
	
};
}

function drawEnvironmentOverheadPopUpChart(chartData){
	var dataArray = [];
	var options = {
		legend : { position : 'none', color : 'black'},
		hAxis : { title : 'Percentage of Employees Required'},
		vAxis : { textStyle : {
				color : 'black',
				fontName : 'Chango',
				fontSize : 10.5
			},
			tooltip : {
				trigger : 'selection'
			},
			format : '#%'
		},
		 colors: ['#009933'],
		chartArea : {
			width : "60%",
			height : "60%",
			left: 200
		},
		};

	var gdata = new google.visualization.DataTable();
	gdata.addColumn("string", "Broad Occupation");
	gdata.addColumn("number", "occupational Percentage");
	$.each(chartData,function(i, obj) {
				dataArray.push([ obj.braodOccupation,obj.occupationPercentage ]);
			});

	gdata.addRows(dataArray);

	var chart = new google.visualization.BarChart(document.getElementById('Popup_BarChart_div'));
	var formatter = new google.visualization.NumberFormat({
		suffix : '%'
	});
	formatter.format(gdata, 1);
	chart.draw(gdata, options);
}

function loadData(selected){
			$.get("http://" + window.location.host + "/ORSDBWeb/rest/EnvSvc/getEnvData/", 
			{selected : selected}, 
			function(data, status)
			{
				jsonData = data;
				drawCharts(data);
				drawOverAllDataTable(data);
			}
			,'json');
}



